<?php

class Application_Model_ProductOrderMapper {
	
	protected $_dbTable;
	
	public function setDbTable($dbTable){
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable(){
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_CartProduct');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_ProductOrder $productOrder){
		$data = array(
				'id_order' => $productOrder->getIdOrder(),
				'id_product' => $productOrder->getIdProduct(),
		);
	
		$this->getDbTable()->insert($data);
	}
	
	public function find($id, Application_Model_ProductOrder $productOrder){
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$productOrder->setIdOrder($row->id_order)
			->setIdProduct($row->id_product);
	}
	
	public function fetchAll() {
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_ProductOrder();
			$entry->setIdOrder($row->id_order)
				->setIdProduct($row->id_product);
			$entries[] = $entry;
		}
		return $entries;
	}
	
	public function getProductIdsForOrder($idOrder){
		$resultSet = $this->getDbTable()->fetchAll(array(" id_order = ?" => $idOrder));
		
		$ids = array();
		foreach ($resultSet as $row) {
			$ids[] = $row->id_product;
		}
		return $ids;
	}
}

